<?php

namespace app\api\controller;

use alipay\aop\AopClient;
use app\common\controller\Api;
use app\common\library\Pay;
use app\common\model\MoneyLog;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\Order;
use app\common\model\product\Member as ProductMember;
use app\common\model\User;
use app\common\model\user\Log as UserLog;
use think\Db;
use think\Log;

/**
 * 回调接口
 */
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 回调
     */
    public function alipayNotify()
    {
        $post = $_POST;
        if (empty($post)) { //判断POST来的数组是否为空
            return false;
        }
        Log::write('记录日志：' . json_encode($post), 'err');
        $post['fund_bill_list'] = htmlspecialchars_decode($post['fund_bill_list']);
        $aop = new AopClient();
        $alipayrsaPublicKey = config('site.alipay_public_key');
        $check = $aop->rsaCheckV1($post, $alipayrsaPublicKey, "RSA2");
        Log::write('验证结果:' . json_encode($check));
        extract($post);
        if ($check) {
            //商户订单号
            //支付宝交易号
            if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {
                $str = substr($out_trade_no, 0, 2);
                if ($str == 'NO') {
                    Pay::orderFulfillment($out_trade_no, 1, $trade_no);
                }
                if ($str == 'UL') {
                    $log = UserLog::get(['sn' => $out_trade_no]);
                    if ($log->p_id) {
                        $puser = User::get($log->p_id);
                        $puser->setInc('total_interests', $log->p_interests);
                    }
                    $user = User::get($log->user_id);
                    $user->setInc('use_dividend', $log->dividend);
                    $user->setInc('total_interests', $log->interests);
                    $log->save(['state' => '1', 'paytime' => time(), 'transaction_id' => $trade_no]);
                }
                echo "success";
            } else {
                Log::error('trade_status不存在:');
            }
        } else {
            //验证失败
            echo "fail";   //请不要修改或删除
        }
    }

    /**
     * 微信回调
     */
    public function wechatNotify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'WYa96C3GM2PLVt4opEhKwJdez59043qn');
            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            // Db::name('pay_log')->insert(['data' => $orderData]);
            $orderData = json_decode($orderData, true);
            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'order':
                            Pay::orderFulfillment($order_sn, 0, $transaction_id);
                            
                            break;
                        case 'dividend':
                            $log = UserLog::get(['sn' => $order_sn]);
                            if ($log->p_id) {
                                $puser = User::get($log->p_id);
                                $puser->setInc('total_interests', $log->p_interests);
                            }
                            $user = User::get($log->user_id);
                            $user->setInc('use_dividend', $log->dividend);
                            $user->setInc('total_interests', $log->interests);
                            $user->save(['group_id' => $log->group_id]);
                            $log->save(['state' => '1', 'paytime' => time(), 'transaction_id' => $transaction_id]);
                            break;
                    }
                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
}
